/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int count = 0;
        ListNode *newHead = new ListNode(-1);
        newHead->next = head;
        ListNode *fast = head, *slow = head, *prev = newHead;
        for (; count < n; count++) {
            if (fast == nullptr) break;
            fast = fast->next;
        }
        if (count < n) return head;
        while (fast) {
            fast = fast->next;
            slow = slow->next;
            prev = prev->next;
        }
        prev->next = slow->next;
        return newHead->next;
    }
};
